//
//  OrderCancleCtr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/27.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import soapp
import Eelay
//import TPKeyboardAvoiding

private var reasons:TP.options = [
    ["id":"下错订单".loc,"name":"下错订单".loc],
    ["id":"报价太慢".loc,"name":"报价太慢".loc],
    ["id":"已超时".loc,"name":"已超时".loc],
    ["id":"测试一下并无需求".loc,"name":"测试一下并无需求"],
    ["id":"其它原因".loc,"name":"其它原因".loc],

]


open class OrderCancleCtr:EeAlertView,TableVConfig
{
    
    open override var intrinsicContentSize: CGSize{
        return [300,200]
    }
    
    open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        
    }
    
    
    public let sections:TP.section = [
        [
//            [
//                "#back_hex":"#0000",
//                "id":"options",
//                FK.options:reasons,
//                FK.selectMode:TagSelectMode.singleToggle.value,
//                FK.field:StrField(id: "options", defaultV: "", need: false, hiden: false, rule:
//                    JoRule(reg: "^[\\s\\S]{1,1000}$", nil_msg: "选择取消原因", err_msg: "选择取消原因")),
//                ],
            [
                "id":"reason",
                FK.fields:[
                    [
                        FK.placeholder:"请输入取消[XX]的原因".replaceVars(values: OrderScheme.default.name),
                        FK.field:StrField(id: "remark", defaultV: "", need: false, hiden: false, rule:
                        JoRule(reg: "^[\\s\\S]{1,10000}$", nil_msg: "请输入取消[XX]的原因".replaceVars(values: OrderScheme.default.name), err_msg: "请输入取消[XX]的原因".replaceVars(values: OrderScheme.default.name))),
                    ],
                ]
            ]
        ]
    ]
    
    public let selector:TP.selector = [
        "id<options>":ReasonSelectorCell<OptionView>.self,
        "id<reason>":MarkCell<line.px80>.self,
        "id<__blank>":BlankLine<line.px10>.self,
        ]
    
    public var canleSuccess:(()->Void) = {}
    
    public let tableView = TPKeyboardAvoidingTableView(frame: [0], style: .plain)
    
    
    public let deleteBt = UIButton()
    let button = UIButton()
    
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        let img = UIImage(named:"delete_tag")?.dynamicImage(color: ._foreground)
        button.setImage(img, for: .normal)
    }
    open override func addLayoutRules() {
        
        let header = TitleHeader()
        let footer = Footer()
    
        self.enableTouchDismiss = false
        self.centerOffset = [0,-50]
        self.eelay = [
            [header,[ee.T.L.R]],
            [footer,[ee.L.B.R]],
            [tableView,[header,ee.B,ee.T],[footer,ee.T,ee.B],[ee.L.R]],
        ]
        self.configTables(tables: tableView)
        
        tableView.buildDynamicHeight()
        tableView.separatorStyle = .none
        tableView.load(sections: sections, selector: selector)
        tableView.backgroundColor = .clear
        
        
        self.backgroundColor = UIColor._background
        
        let img = UIImage(named:"delete_tag")?.dynamicImage(color: ._foreground)
        button.setImage(img, for: .normal)
        self.eelay = [
            [button,[header,ee.Y],[ee.R,-AppTheme.edge],"30",30]
        ]
        
        self.backgroundColor = ._background
//        let effect = UIBlurEffectStyle.light
//        let blurView = UIVisualEffectView(effect:  UIBlurEffect(style: effect))
//        self.insertSubview(blurView, at: 0)
//
//        blurView.append([ee.T.L.B.R])
        button.contentEdgeInsets = [6,6]
        button.addTarget(self, action: #selector(canle), for: .touchUpInside)
        footer.confirmBt.addTarget(self, action: #selector(submit), for: .touchUpInside)
        
    }
    

    @objc open func canle()
    {
        self.touchBK?.dismiss()
    }
    
    @objc open func submit() {
        let info = JoPaw.paw(tableView: tableView)
        
        if info.validate
        {
            
            
            var remark = ""
//            if let options = info.values["options"] as? String
//            {
//                if options != ""
//                {
//                    remark = options + "#"
//                }
//            }
            
            if let reason = info.values["remark"] as? String
            {
                if reason != ""
                {
                    remark = remark + reason
                }
            }
            
            if remark == ""
            {
                
                "请填写取消[XX]的原因".replaceVars(values: OrderScheme.default.name).alert()
                return
            }
            
            HUD.share.show().mode(.indeterminate)

            var params = [String:Any]()
            params["remark"] = remark
            params["orderid"] = mo.model["order.id",""]
            
            weak var wself = self
            
            JoTask().post.log._surl(.取消订单).params(params).json_handle({ (status, message, obj, response) in
                HUD.share.hide(animated: true)
                if status.isSuccess{
                    "[XX]已取消".replaceVars(values: OrderScheme.default.name).alert()
                    wself?.canle()
                    wself?.canleSuccess()
                
//                    guard let ws = wself else{return}
                    return
                }
                message.alert()
            }).run()
        }
    }
    
}

extension OrderCancleCtr
{
    
    
    public class MarkCell<Line:LineHeight>: FieldCell {
        
        var textV = TextAreaField()
        override public func addLayoutRules() {
            //        let w = Int(FieldCell.name_width)
//            let t = Int(FieldCell.padding_top)
//            let b = Int(FieldCell.padding_bottom)
//            let l = Int(FieldCell.padding_left)
            
            contentView.eelay = [
                [textV,"\(Line.height)",[ee.T.L.B.R,[4,AppTheme.edge,-10,-AppTheme.edge]]],
            ]
            self.indicator = .none
            
            titleL.setContentConstrainToHighLever()
            requiredMark.ui.font18.text("*").text(color: .clear)
            rightIcon.ui.font(size: 13).ncolor(color: ._foregroundWeak)
            _ = titleL.ui.font15.text(color: ._foreground)
            backgroundColor = ._background
        }
        
        open override func mo_model_reload() {
            self.titleL.text = mo.model["title",""]
//            contentView.fillData(model: mo.model)
            
            if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.field)", mo.model)
            {
                textV.mo.model = f
            }
            else
            {
                if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
                {
                    textV.mo.model = f
                }
            }
            textV.valueT.bsui.background(color: UIColor.color(light: "#f1f1f1", dark: "#ccc1"))
        }
        
    }
    public class OptionView: FOptionV {
        public override var intrinsicContentSize : CGSize {
            let s_w:CGFloat = Swidth - 2*AppTheme.edge
            let s_h:CGFloat = 50
            return CGSize(width: s_w, height: s_h)
        }
        
        public override func mo_model_reload() {
            super.mo_model_reload()
        }
        
        public override func setOptionLayout() {
            titleL.text = ""
            titleL.font = UIFont.systemFont(ofSize: 16)
            let lineV = UIView()
            self.eelay = [
                [titleL,[ee.T.L.B.R,[8,50,-8,-8]]],
                [imgV,[ee.Y],[ee.L,10],"26",26],
                [bt,[ee.T.L.R.B]],
                [lineV,"0.5",[ee.L.R.B]],
            ]
            
            _ = titleL.ui.text(color: ._foreground).font15
            lineV.bsui.background(hex: "#aaa")
        }
    }
    
    public class ReasonSelectorCell<Kit:FOptionV>: FieldCell {
        
        public var field1 = TagsOptionField<Kit>()
        
        public override func addLayoutRules() {
            titleL.ui.font13.text(color: ._foreground).node("title")
            let w = Int(FieldCell.name_width)
            //        let t = Int(FieldCell.top)
            
            contentView.eelay = [
                [titleL,[ee.T.L,[8,12]],"21",.<w],
                [requiredMark,[titleL,ee.Y,3],[titleL,ee.R,ee.L,2]],
                [__line,[ee.L.B.R,[10,0,-10]],"0.5"]
            ]
            
            self.indicator = .none
            titleL.setContentConstrainToHighLever()
            requiredMark.ui.font18.text("*").text(color: .clear)
            rightIcon.ui.font(size: 13).ncolor(color: .color(light: "#aaa", dark: "aaa3"))
            contentView.eelay = [
                [field1,[ee.L.B.R,[12,-8,-12]],[titleL,ee.B,ee.T,16]],
            ]
            field1.tagsV.preferredMaxLayoutWidth = Swidth - 2*AppTheme.edge
            field1.insets = 0
            field1.lineSpace = 0
            field1.backgroundColor = .clear
            contentView.backgroundColor = .clear
            self.backgroundColor = .clear
        }
        
        
        public override func mo_model_reload() {
            titleL.text = mo.model["title",""]
//            field1.controller = self.content_controller
            if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.field)", mo.model)
            {
                field1.mo.model = f
            }
            else
            {
                if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
                {
                    field1.mo.model = f
                }
            }
        }
    }
    
    public class TitleHeader: JoView {
        public var titleL = UILabel()
        
        public override func addLayoutRules() {
            let __line = UIView()
            
            eelay = [
                [titleL,[ee.T.L.B.R,[14,10,-14,-10]]],
                [__line,[ee.L.B.R],"1"]
            ]
//            __line.backgroundColor = UIColor(shex:__main_hex)
//            contentView.backgroundColor = .white
            self.backgroundColor = .clear
            titleL.ui.font16.text(color: ._foreground).center.text("取消订单".loc)
            
        }
    }
    
    class Footer: JoView {
        var confirmBt = UIButton()
        
        override func addLayoutRules() {
            eelay = [
                [confirmBt,[ee.X.T.B,[0,10,-20]]],
            ]
  
            self.backgroundColor = .clear
            confirmBt.ui.font(size: 14).ncolor(color: ___shop.tint).ntitle(title: "确定".loc).set(radius: 3, width: 1, color: ___shop.second)
            confirmBt.contentEdgeInsets = [6,36]
            
        }
      
    }
    
    
    
    
    
}
